package com.yinxing.framework.shiro.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yinxing.framework.domain.R;
import com.yinxing.framework.enums.RCode;
import com.yinxing.framework.shiro.exception.RequiresAuthenticationException;
import com.yinxing.framework.shiro.exception.RequiresUserException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
public class ShiroJsonOutPutFilter implements Filter {

    private ObjectMapper objectMapper;

    @Override
    public void init(FilterConfig filterConfig) {
        log.debug("ShiroJsonOutPutFilter 初始化...");
        WebApplicationContext wac = WebApplicationContextUtils.findWebApplicationContext(filterConfig.getServletContext());
        if (wac == null) {
            throw new IllegalStateException("No WebApplicationContext found: " +
                    "no ContextLoaderListener or DispatcherServlet registered?");
        }
        this.objectMapper = wac.getBean(ObjectMapper.class);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws ServletException {
        Throwable cause = null;

        try {
            chain.doFilter(req, rsp);
        } catch (Throwable e) {
            cause = e.getCause();
        }

        if (cause != null ) {
            if(cause instanceof ShiroException) {
                String requestURI = ((HttpServletRequest) req).getRequestURI();
                String errorMsg = String.format("当前URL[%s]拒绝访问.%s", requestURI, cause.getMessage());
                if(cause instanceof RequiresAuthenticationException || cause instanceof RequiresUserException) {
                    this.writeToReponse(rsp, R.err(errorMsg, RCode.ACCOUNT_UNAUTHENTICATED));
                } else {
                    this.writeToReponse(rsp, R.err(errorMsg, RCode.ACCESS_UNAUTHORIZED));
                }
            } else {
                throw new ServletException(cause);
            }
        }
    }

    /**
     * 把对象输出到响应流中
     * @param response HttpResonse
     * @param r 输出信息
     * @throws ServletException
     */
    private void writeToReponse(ServletResponse response, R r) throws ServletException {
        response.setContentType("application/json;charset=UTF-8");
        try {
            objectMapper.writeValue(response.getOutputStream(), r);
        } catch (IOException e) {
            throw new ServletException(e);
        }
    }

    @Override
    public void destroy() {
        log.debug("ShiroJsonOutPutFilter 销毁...");
    }
}
